package ca.cbc.localsrvextadmin.converter;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import ca.cbc.giscommon.util.GeometryUtil;

import com.opensymphony.xwork2.conversion.TypeConversionException;
import com.vividsolutions.jts.geom.Geometry;

public class GeometryConverter extends StrutsTypeConverter {

	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Geometry geo = null;
        if (values != null && values.length > 0 && values[0] != null && values[0].length() > 0) {
        	String point = values[0];
        	geo = GeometryUtil.instance.parsePoint(point);
        	if(geo == null) 
        		throw new TypeConversionException("Failed to convert to Geometry: " + point);
        }
		return geo;
	}

	@Override
	public String convertToString(Map context, Object o) {
		String value = null;
		if (o instanceof Geometry) {
			Geometry geo = (Geometry) o;
			value = String.valueOf(geo.getCoordinate().x) + "," +  String.valueOf(geo.getCoordinate().y); 
		}
		return value;
	}

}
